<template>
  <x-layout-main>
    <template #header>
      <n-tabs v-model:value="templateType" type="card" @update:value="handleRefresh">
        <n-tab-pane :name="0" tab="广告主"> </n-tab-pane>
        <n-tab-pane :name="1" tab="商务管家"> </n-tab-pane>
        <n-tab-pane :name="2" tab="代理商"> </n-tab-pane>
      </n-tabs>
    </template>
    <div class="m-dashboard">
      <div class="g-container">
        <div class="g-content">
          <x-form ref="formRef" v-model:model="form" inline wrap label-placement="left" size="small">
            <n-form-item v-if="templateType === 0" label="账户主体">
              <n-select v-model:value="form.mdmName" placeholder="请选择" :options="companyList" clearable filterable />
            </n-form-item>
            <n-form-item label="账号状态">
              <n-select v-model:value="form.systemStatus" placeholder="请选择" :options="systemStatusList" clearable filterable />
            </n-form-item>
            <n-form-item label="余额情况">
              <n-select
                v-model:value="form.balanceStatus"
                placeholder="请选择"
                :options="balanceStatusList"
                clearable
                filterable
              />
            </n-form-item>
            <n-form-item label="账户ID">
              <n-input v-model:value="form.accountCode" placeholder="账户ID" clearable></n-input>
            </n-form-item>
            <n-form-item label="账户名称">
              <n-input v-model:value="form.accountName" placeholder="账户名称" clearable></n-input>
            </n-form-item>
            <n-form-item label="所属人员">
              <n-select
                v-model:value="form.accountId"
                placeholder="所属人员"
                :options="accountList"
                value-field="accountId"
                label-field="accountName"
                filterable
                clearable
              />
            </n-form-item>
            <x-button size="small" type="primary" @click="handleSubmit">查询</x-button>
            <x-button size="small" @click="handleRefresh">重置</x-button>
          </x-form>
        </div>
        <div class="g-content">
          <div>
            <x-button size="small" type="primary" @click="handleCreate()">添加账户</x-button>
            <x-button :disabled="checkedIds.length === 0" size="small" type="primary" @click="handlePeople()"
              >批量分配人员</x-button
            >
          </div>
          <div>
            <x-data-table
              ref="tableRef"
              v-model:immediate="immediate"
              v-model:checked-row-keys="checkedIds"
              :params="paginationParams"
              :columns="columns"
              :row-key="(row) => row.accountCode"
              row-class-name="text-sm"
              max-height="infinite"
            />
          </div>
        </div>
      </div>
    </div>
    <auth-modal v-if="authModalData.show" :modal-data="authModalData" @success="handleSubmit" />
    <export-modal
      v-if="exportModalData.show"
      :modal-data="exportModalData"
      :account-list="accountList"
      @success="handleSubmit"
    />
    <EditPeopleModal
      v-if="peopleModalData.show"
      :modal-data="peopleModalData"
      :account-list="accountList"
      @success="handleSubmit"
    />
  </x-layout-main>
</template>

<script setup lang="ts">
  import { ref, computed, h, onMounted } from 'vue'
  import { XForm, XButton, XDataTable, XLayoutMain } from '@/components'
  import { NFormItem, NSelect, NInput, NSpace, NText, NTabs, NTabPane, NPopconfirm } from 'naive-ui'
  import { useStore } from '@/store'
  import { useDictionary } from '@/hooks'

  import AuthModal from '@/views/account/components/AuthModal.vue'
  import ExportModal from '@/views/account/components/exportModal.vue'
  import EditPeopleModal from '@/views/account/components/EditPeopleModal.vue'
  const store = useStore()
  const { get: getDic, find: findDic } = useDictionary()
  const checkedIds = ref([])

  const exportModalData = ref({
    show: false,
    id: null
  })
  const authModalData = ref({
    show: false,
    redirectUri: null
  })
  const peopleModalData = ref({
    show: false,
    checkedIds: checkedIds.value || []
  })
  const redirectUri = ref(null)
  const templateType = ref(0)
  const tableRef = ref(null)
  const formRef = ref(null)
  const form = ref({
    mdmName: null,
    systemStatus: null,
    balanceStatus: null,
    accountCode: null,
    accountName: null,
    accountId: null
  })
  const companyList = ref([])
  const systemStatusList = ref([
    {
      label: '有效',
      value: 'CUSTOMER_STATUS_NORMAL'
    },
    {
      label: '不可用',
      value: 'CUSTOMER_STATUS_ERROR'
    }
  ])
  const balanceStatusList = ref([
    {
      label: '查看为0的账户',
      value: 0
    },
    {
      label: '查看不为0的账户',
      value: 1
    }
  ])
  const accountList = ref([])
  const immediate = ref(true)
  const paginationParams = computed(() => {
    return {
      actions: 'system/mediaAccountList',
      data: {
        ...form.value,
        accountType: templateType.value
      }
    }
  })
  const columns = computed(() => {
    const arr = [
      {
        type: 'selection',
        key: 'selection',
        fixed: 'left',
        checkedRowKeys: checkedIds.value
      },
      {
        title: '账户ID',
        key: 'accountCode',
        width: 120
      },
      {
        title: '账户名称',
        key: 'accountName',
        width: 120
      },
      {
        title: '授权状态',
        key: 'oauthStatus',
        width: 120
      },
      {
        title: '账号状态',
        key: 'systemStatus',
        width: 120
      },
      {
        title: '登录账户',
        key: 'loginName',
        width: 120
      },
      {
        title: '账户余额',
        key: 'accountBalance',
        width: 120
      },
      {
        title: '授权来源',
        key: 'accountRoleType',
        width: 120,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(NText, {}, () => row.accountRoleType),
            row.accountUin ? h(NText, {}, () => row.accountUin) : null
          ])
        }
      },
      {
        title: '广告主行业',
        key: 'systemIndustryName',
        width: 120
      },
      {
        title: '账户主体',
        key: 'mdmName',
        width: 120
      },
      {
        title: '所属人员',
        key: 'ownerName',
        width: 120
      },
      {
        title: '操作',
        key: 'action',
        width: 120,
        render(row: any) {
          return h(NSpace, () => [
            row.systemStatus === '不可用'
              ? h(
                  XButton,
                  {
                    type: 'primary',
                    text: true,
                    onClick: () => handleCreate()
                  },
                  () => '授权'
                )
              : null,
            templateType.value !== 0
              ? h(
                  XButton,
                  {
                    type: 'primary',
                    text: true,
                    onClick: () => handleExportAccount(row)
                  },
                  () => '导入账户'
                )
              : null,
            h(
              NPopconfirm,
              { onPositiveClick: () => handleDelete(row) },
              {
                default: () => '确定要删除此媒体账号？',
                trigger: () =>
                  h(
                    XButton,
                    {
                      type: 'primary',
                      text: true
                    },
                    () => '删除'
                  )
              }
            )
          ])
        }
      }
    ]
    if (templateType.value === 1 || templateType.value === 2) {
      const index = arr.findIndex((t) => t.key === 'systemIndustryName')
      arr.splice(index, 1)
      const index1 = arr.findIndex((t) => t.key === 'mdmName')
      arr.splice(index1, 1)
    }
    return arr
  })

  onMounted(() => {
    getAccountList()
    getRedirectUri()
    getCompanyList()
  })

  const getRedirectUri = async () => {
    const { data } = await store.dispatch('system/mediaAccountGetRedirectUri')
    redirectUri.value = data
  }
  const getAccountList = () => {
    store
      .dispatch('system/accountList', {
        pageSize: 10000
      })
      .then((res) => {
        accountList.value = res.data
      })
  }
  const getCompanyList = () => {
    store
      .dispatch('system/mediaAccountMdmNameList', {
        pageSize: 10000
      })
      .then(({ data }) => {
        const list: { value: any; label: any }[] = []
        data.forEach((item: any) => {
          list.push({
            value: item,
            label: item
          })
        })
        companyList.value = list
      })
  }
  const handleExportAccount = (row: any) => {
    exportModalData.value = {
      show: true,
      id: row.id
    }
  }

  const handleSubmit = () => {
    checkedIds.value = []
    immediate.value = true
  }
  const handleRefresh = () => {
    formRef.value.resetFields()
    handleSubmit()
  }

  const handleDelete = async (row: any) => {
    await store.dispatch('system/mediaAccountDelete', { id: row.id })
    handleSubmit()
  }

  const handleCreate = () => {
    window.open(`${redirectUri.value}`, '_blank')
    authModalData.value = {
      show: true,
      redirectUri: redirectUri.value
    }
  }
  const handlePeople = () => {
    peopleModalData.value = {
      show: true,
      checkedIds: checkedIds.value
    }
  }
</script>

<style lang="scss" scoped>
  .m-dashboard {
    height: calc(100vh - 70px);
    .help {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 90px;
      height: 90px;
      color: #ffffff;
      border-radius: 4px;
      margin: 10px;
      background: url('../../assets/images/help-2.png') no-repeat left,
        url('../../assets/images/help-1.png') no-repeat 85% / auto 100%, linear-gradient(90deg, #717aff, #5a67ff);
      cursor: pointer;

      .title {
        font-size: 20px;
        margin-bottom: 5px;
        font-weight: 600;
      }
    }
    .welcome {
      padding-top: 250px;
      text-align: center;
      font-size: 40px;
    }
  }
</style>
